package cn.java75.sp.web;

import cn.java75.sp.entity.*;
import cn.java75.sp.service.StudentService;
import cn.java75.sp.vo.AjaxResult;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author oldliu
 * @since 1.0
 */
@RestController
@RequestMapping("student")

//@ApiOperation("学生操作")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @Value("${upload.path}")
    private String picpath;

    //web对象
    //请求参数
    @PreAuthorize("hasAuthority('searchstu')")
    @GetMapping("search")
    @ApiOperation("学生查询")
    public Page<Student> search(@ApiParam("页号") @RequestParam(name = "pageNo", defaultValue = "1") int pageNo, @ApiParam("页大小，默认为10") @RequestParam(name = "pageSize", defaultValue = "10") int pageSize, @ApiParam("姓名的模糊搜索条件") String sname, @ApiParam("QQ的模糊搜索条件") String qq, @ApiParam("电话的模糊搜索条件") String telephone, HttpServletRequest request) {
        Page<Student> p = this.studentService.search(pageNo, pageSize, sname, qq, telephone, null, null);

        return p;
    }

    @GetMapping("/toAdd")
    public String toAdd() {
        return "addstudent";
    }

    //    @ApiOperation("学生添加")
////    @ApiImplicitParams(@ApiImplicitParam(name = "idcardpic2",value = "身份证照片"))
////    @PostMapping("add")
////    public String add(Student stu, @RequestParam(name = "idcardpic2", required = false) MultipartFile idcard, HttpServletRequest request) {
////
////        if (idcard.isEmpty() == false) {
////            String filename = idcard.getOriginalFilename();
////            String suffix = filename.substring(filename.lastIndexOf('.'));
////            String newName = UUID.randomUUID() + suffix;
////            ServletContext app = request.getServletContext();
////            String images = picpath;//app.getRealPath("images");
////            File f = new File(images);
////            if (f.exists() == false)
////                f.mkdirs();
////            try {
////                idcard.transferTo(new File(f, newName));
////                stu.setIdcardpic(newName);
////            } catch (IOException e) {
////                e.printStackTrace();
////            }
////        }
////        int add = studentService.add(stu);
////        if (add > 0)
////            return "redirect:/student/search";
////
////        //return "/WEB-INF/jsp/addstudent.jsp";
////        return "addstudent";
////    }

    @PreAuthorize("hasAuthority('stuadd')")
    @ApiOperation("学生添加")
    @ApiImplicitParams(@ApiImplicitParam(name = "idcardpic2", value = "身份证照片"))
    @PostMapping("add")
    public AjaxResult add(@Valid Student stu, @RequestParam(name = "idcardpic2", required = false) MultipartFile idcard, HttpServletRequest request) {
//        if(stu.getSname().length()<2){
//
//        }
        System.out.println("stu======="+stu);
        if (idcard.isEmpty() == false) {
            ////idcard.getBytes()
            String filename = idcard.getOriginalFilename();
            String suffix = filename.substring(filename.lastIndexOf('.'));
            String newName = UUID.randomUUID() + suffix;
            ServletContext app = request.getServletContext();
            String images = picpath;//app.getRealPath("images");
            File f = new File(images+"/pic");
            if (f.exists() == false)
                f.mkdirs();
            try {
                idcard.transferTo(new File(f, newName));
                stu.setIdcardpic(newName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        int add = studentService.add(stu);
        //
        return AjaxResult.success("添加成功");
    }

//    @GetMapping("show/{stuno}")
//    public AjaxResult get(@PathVariable  long stuno){
//        Student student = this.studentService.get(stuno);
//        return AjaxResult.success(student);
//    }
    //1,2,3,4
    //del/1,2,4,5,6
    @GetMapping("del/{stuno}")
    public AjaxResult del(@PathVariable("stuno") long id) {
        //try {
        Student student = new Student();
        student.setStuno(id);
        int del = this.studentService.del(student);
        return del > 0 ? AjaxResult.success() : AjaxResult.error("此学生不能删除");
//        }catch (Exception e){
//            e.printStackTrace();
//            return AjaxResult.error("删除失败！");
//        }
    }

    @PreAuthorize("hasAuthority('stushow')")
    @GetMapping("get/{stuno}")//    get/123
    public AjaxResult get(@PathVariable("stuno") long stuno) {
        Student student = this.studentService.get(stuno);
        return AjaxResult.success(student);//obj.data.sname
    }

    @PostMapping("update/{stuno}")
    public AjaxResult update(@PathVariable("stuno") long stuno, Student stu) {
        stu.setStuno(stuno);
        this.studentService.update(stu);
        return AjaxResult.success();
    }

    @InitBinder
    public void initDate(WebDataBinder web) {
        web.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
    }
}
